package it.intecs.pisa.smarcos.services;

import android.app.Service;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;
import ca.uol.aig.fftpack.RealDoubleFFT;


public class AudioProcessingService extends Service {
	private static final String TAG = AudioProcessingService.class.getSimpleName();
	public static final String ISTART_SRV = "it.intecs.pisa.smarcos.services.AudioProcessingService";
	
	
	
	int frequency = 8000;
	int channelConfiguration = AudioFormat.CHANNEL_IN_MONO;
	int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	
	private RealDoubleFFT transformer;
	int blockSize = 256;
	Button startStopButton;
	boolean started = false;


	/** Called when the service is first created. */
	@Override
	public void onCreate() {
		super.onCreate();
		transformer = new RealDoubleFFT(blockSize);
	
		start();
	}
	
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	private void start() {
		try {
			int bufferSize = AudioRecord.getMinBufferSize(frequency,
					channelConfiguration, audioEncoding);
			AudioRecord audioRecord = new AudioRecord(
					MediaRecorder.AudioSource.DEFAULT, frequency,
					channelConfiguration, audioEncoding, bufferSize);

			short[] buffer = new short[blockSize];
			double[] toTransform = new double[blockSize];
			audioRecord.startRecording();
			while (started) {
				int bufferReadResult = audioRecord.read(buffer, 0, blockSize);

				for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
					toTransform[i] = (double) buffer[i] / 32768.0; // signed 16 bit
				}

				transformer.ft(toTransform);
				searchPeak(toTransform);
			}
			audioRecord.stop();
		} catch (Throwable t) {
			Log.e("AudioRecord", "Recording Failed");
		}
	}
	
	void searchPeak(double[] values){
		for (int i = 0; i < values.length; i++) {
			Log.d(TAG, i + " " + values);
		}
	}
	
	
}